import React, { Component } from 'react';

import { Flex, Modal, Icon, ActivityIndicator,Toast } from 'antd-mobile';
import 'antd-mobile/lib/flex/style/index.css';
import 'antd-mobile/lib/modal/style/index.css';
import 'antd-mobile/lib/icon/style/index.css';
import 'antd-mobile/lib/toast/style/index.css';
import 'antd-mobile/lib/activity-indicator/style/index.css';
import {getQueryString} from '../utils/util';
import closest from 'antd-mobile/lib/_util/closest';

import {CopyToClipboard} from 'react-copy-to-clipboard';

import { get } from  '../api/getData';
import host from  '../config/host';

import '../static/styles/detail.css';

import wxUtils from '../utils/wxUtils';

import xiaobain from '../static/icon/xiaobian.jpg';

const is = require('@methodgrab/is');

class GoodsInfo extends Component {
    constructor(props) {
        super(props);

        this.state = {
            disableCopy:false,
            showtaosec:false,
            copied: false,
            goods_name:"",
            goods_pic:"",
            guid_content:"",
            id:1,
            quan_fee:0,
            sales:0,
            sales_price:0,
            taoke_price:0,
            taosec:"",
            tbid:"",
            tmall:1,
            update_time:"",
            url:"",
            coupon_invalid:0,
            shareImgUrl: null,
            animating : false,
            shareImg: '',
            showShareImg:false,
            shareImgStatus:false,
        };
    }
    componentDidMount(){
        let __this = this;
        let token = localStorage.getItem('token');
        let shareImgUrl = host.shareImgUrl.replace('{tbid}', this.props.match.params.tbid).replace('{token}', token);
        this.setState({
            shareImgUrl: shareImgUrl
        });
        get('/api/goods/' + this.props.match.params.tbid , {from : this.props.match.params.from} , function (error , data) {
            if(error === null) {
                __this.setState(data);
                document.title = data.goods_name;
                __this.convertUrl();
                wxUtils.share({
                    link:window.location.href,
                    description:'我是领了'+data.quan_fee+'元的券购买的'+data.goods_name+',你也来领券购买吧！能省不少呢！',
                    title : '我是领了'+data.quan_fee+'元的券购买的'+data.goods_name,
                    imgUrl: data.goods_pic,
                });
            }else{
                Toast.fail('获取失败,刷新重试');
            }
        });


        let ios = is.ios();
        if (ios) {
            let version = is.iosVersion();
            if (version.major < 10) {
                __this.setState({disableCopy : true});
            }
        } else{
            __this.setState({disableCopy : true});
        }

        document.body.style.overflow = 'auto';
    }

    convertUrl(){
        let __this = this;
        this.setState({
            animating:true
        });
        get('/api/convert/url', {tbid:__this.props.match.params.tbid}, function(error, data){
            if(error === null){
                __this.setState({
                    taosec : data.taosec,
                    animating : false
                });
            }else{
                Toast.fail('获取失败了，刷新重试');
            }
        });
    }

    // iOS8 以及iOS9 不支持copy，需要用户手动copy
    selectCode() {
        var input = document.getElementById('copy');
        input.focus();

        var range = document.createRange();
        range.selectNodeContents(input);

        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);

        input.setSelectionRange(0, 999999);

    }

    //
    copyCode() {
        // 参考： https://stackoverflow.com/questions/32851485/make-clipboard-copy-paste-work-on-iphone-devices

        var input = document.getElementById('copy');
        var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);

        if (isiOSDevice) {
            var editable = input.contentEditable;
            var readOnly = input.readOnly;

            input.contentEditable = true;
            input.readOnly = true;

            var range = document.createRange();
            range.selectNodeContents(input);

            var selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);

            input.setSelectionRange(0, 999999);
            input.contentEditable = editable;
            input.readOnly = readOnly;
        } else {
            input.select();
        }

        document.execCommand('copy');
        input.blur();
        this.showModal('showtaosec');
    }

    showModal(){
        this.setState({
            copied : true,
        });
    };
    closeModal() {
        this.setState({
            copied : false,
        });
    };

    closeDownModal(){
        this.setState({
            coupon_invalid : 0,
        });
    }

    onWrapTouchStart = (e) => {
        // fix touch to scroll background page on iOS
        if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
            return;
        }
        const pNode = closest(e.target, '.am-modal-content');
        if (!pNode) {
            e.preventDefault();
        }
    };

    downShareImg(){
        let _this = this;
        this.setState({
            shareImgStatus:true
        });
        get("/tool/goods/ext/img2/"+_this.props.match.params.tbid, {type:'login',repType:'json'}, function(error, data){
            if(error === null){
                _this.setState({
                    showShareImg: true,
                    shareImg: data.url,
                    shareImgStatus:false
                });
            }else{
                Toast.fail('获取失败了，刷新重试');
            }
        }, 'http://taoke.share.guoxiaoge.cn');
        // window.location.href=this.state.shareImgUrl;
    }

    render() {
        return (
            <div>
                <Modal
                  visible={this.state.showShareImg}
                  transparent
                  closable={true}
                  maskClosable={false}
                  title="长按保存图片"
                  onClose={()=> {this.setState({showShareImg:false})}}
                  wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <div style={{ height: '490', overflow: 'hidden' }}>
                        <img style={{width:'100%'}} src={this.state.shareImg} />
                    </div>
                </Modal>
                <ActivityIndicator
                                toast
                                text="正在获取图片...."
                                animating={this.state.shareImgStatus}
                              />
                <ActivityIndicator
                                toast
                                text="正在生成淘口令..."
                                animating={this.state.animating}
                              />
                <Modal
                    visible={this.state.copied}
                    transparent
                    maskClosable={false}
                    footer={[{ text: ' 知道了', onPress: () => { this.closeModal(); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <div style={{ height: 70, textAlign: 'left', overflow: 'scroll' }}>
                        淘口令{this.state.taosec}复制成功!<br/>
                        赶快打开【手机淘宝】APP领取属于你的{this.state.quan_fee}元优惠券
                    </div>
                </Modal>

                <Modal
                    visible={this.state.coupon_invalid}
                    transparent
                    maskClosable={false}
                    footer={[{ text: ' 知道了', onPress: () => { this.closeDownModal(); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <div style={{ height: 40, textAlign: 'left', overflow: 'scroll' }}>
                        您可能来晚了一步，该优惠券可能已被领完!
                    </div>
                </Modal>

                <div style={{fontSize:'0'}}>
                    <img style={{width:'100%'}} src={this.state.goods_pic} alt=""/>
                </div>
                <Flex direction="column" justify="start" align="start" className="detail-info">
                    <Flex.Item className="detail-info-title">{this.state.goods_name}</Flex.Item>
                    <Flex justify="around" className="detail-info-sales">
                        <Flex.Item className="taobao-price">淘宝价￥{this.state.sales_price}</Flex.Item>
                        <Flex.Item className="sales">已售{this.state.sales}</Flex.Item>
                    </Flex>
                    <Flex.Item className="detail-goods-price-item" style={{width:'100%'}}>
                        <Flex style={{marginTop:'12px'}} justify="between">
                            <div className="detail-goods-price fl">券后价<b><i>￥</i>{this.state.taoke_price}</b></div>
                            <div className="goods-quan shoufa-quan fl"><span>券</span><b><i>￥</i>{this.state.quan_fee}</b></div>
                            <div className="goods-share" onClick={this.downShareImg.bind(this)}>
                                <i className='iconfont icon-connection'></i>分享商品
                            </div>
                        </Flex>
                    </Flex.Item>
                </Flex>
                <Flex className="copy-taosec" direction="column" style={{background:'none'}}>
                    <Flex.Item>
                        <Flex>
                            <Flex.Item className="copy-taosec-input">
                                <input id="copy" defaultValue='aaa' readOnly value={this.state.taosec} type="text" />
                            </Flex.Item>
                            <Flex.Item className="copy-button">
                                <CopyToClipboard text={this.state.taosec}
                                                 onCopy={() => this.setState({copied: true})}>
                                    <div>一键复制</div>
                                </CopyToClipboard>
                            </Flex.Item>
                        </Flex>
                    </Flex.Item>
                    <Flex.Item className="copy-taosec-notice">
                        <span>长按复制上方淘口令，打开手机淘宝购买</span>
                    </Flex.Item>
                </Flex>
                <Flex direction="column" className="xiaobian-box">
                    <Flex.Item style={{width:'100%'}}>
                        <Flex justify="between">
                            <Flex.Item>
                                <Flex justify="between">
                                    <Flex.Item>
                                        <div className="xiaobian">
                                            <img src={xiaobain} alt="小编"/>
                                        </div>
                                    </Flex.Item>
                                    <Flex.Item className="xiaobian-title">
                                        小编介绍
                                    </Flex.Item>
                                </Flex>
                            </Flex.Item>
                            <Flex.Item className="detail-pub-time">
                                {this.state.update_time}前发布
                            </Flex.Item>
                        </Flex>
                    </Flex.Item>
                    <Flex.Item className="xiaobian-content">
                        {this.state.guid_content}
                    </Flex.Item>
                </Flex>
            </div>
        );
    }
}

export default GoodsInfo;
